import React, { useRef } from "react";
import { Editor } from "@tinymce/tinymce-react";
import { commonService } from "@/api/services/commonService";

export default function EditorComponent() {
	const editorRef = useRef(null);

	const log = () => {
		if (editorRef.current) {
			console.log(editorRef.current.getContent());
		}
	};

	const replace = () => {
		if (editorRef.current) {
			var editorContent = editorRef.current.getContent();
			editorContent = editorContent.replace("{{userName}}", "Srini Prabhakara");
			editorRef.current.setContent(editorContent);
		}
	};

	return (
		<>
			<Editor
				tinymceScriptSrc={"/tinymce/tinymce.min.js"}
				onInit={(evt, editor) => {
					editorRef.current = editor;

					// 添加粘贴事件监听
					editor.on("paste", function (e) {
						console.log("Paste event:", e);

						// 获取剪贴板数据
						const clipboardData =
							e.clipboardData || (window as any).clipboardData;
						if (clipboardData) {
							// 获取所有可用的数据格式
							console.log("Available formats:", clipboardData.types);

							// 获取RTF数据
							const rtfData = clipboardData.getData("text/rtf");
							console.log("RTF data:", rtfData);

							// 获取HTML内容
							const htmlData = clipboardData.getData("text/html");
							console.log("HTML data:", htmlData);
						}
					});
				}}
				initialValue=""
				init={{
					smart_paste: true,
					height: 500,
					menubar: false,
					plugins: [
						"advlist",
						"autolink",
						"lists",
						"link",
						"image",
						"charmap",
						"anchor",
						"searchreplace",
						"visualblocks",
						"code",
						"fullscreen",
						"insertdatetime",
						"media",
						"table",
						"preview",
						"help",
						"wordcount",
					],

					toolbar:
						"undo redo | blocks | " +
						"bold italic forecolor | alignleft aligncenter " +
						"alignright alignjustify | bullist numlist outdent indent | " +
						"removeformat | help | image",
					// 自定义图片上传处理
					images_upload_handler: async (blobInfo, progress) => {
						console.log("Uploading image:", blobInfo.filename());
						try {
							const file = blobInfo.blob();
							const response = await commonService.uploadFile(file);
							return response.url;
						} catch (error) {
							console.error("Upload failed:", error);
							throw error;
						}
					},

					// 配置图片上传相关选项
					image_advtab: true,
					image_uploadtab: true,
					automatic_uploads: true,
					// 允许粘贴图片
					paste_data_images: true,
					paste_webkit_styles: "all", // 保留所有样式
					paste_remove_styles_if_webkit: false, // 不移除webkit样式
					paste_filter_drop: false, // 不过滤拖放的内容
					content_style:
						"body { font-family:Helvetica,Arial,sans-serif; font-size:14px }",
				}}
			/>
		</>
	);
}
